package com.lagou.edu.connector.protocol;

import com.lagou.edu.container.Context;
import com.lagou.edu.container.Engine;
import com.lagou.edu.container.Host;
import com.lagou.edu.container.Wrapper;
import com.minicat.servlet.Servlet;

/**
 * @author liangzj
 * @date 2021/4/10 13:16
 */
public class Mapper {

    private Engine engine;

    public Mapper(Engine engine) {
        this.engine = engine;
    }

    public Servlet mappedServlet(String hostName, String url) {
        Host host = engine.getHosts().stream().filter(host0 -> host0.getName().equals(hostName))
                .findFirst().orElse(null);
        if (host == null) {
            System.out.println("host not found");
            return null;
        }

        Context context = host.getContexts().stream().filter(context0 -> url.startsWith(context0.getName()))
                .findFirst().orElse(null);
        if (context == null) {
            System.out.println("context not found");
            return null;
        }

        Wrapper wrapper = context.getWrappers().stream()
                .filter(wrapper0 -> wrapper0.getServletUrlPatterns().contains(url.replaceFirst(context.getName(), "")))
                .findFirst().orElse(null);
        if (wrapper == null) {
            System.out.println("wrapper not found");
            return null;
        }

        return wrapper.getServlet();

    }

}
